package com.run2code.idea.plugin.codegenerate.biz.generate.template;

import freemarker.cache.FileTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.File;
import java.io.IOException;

/**
 * 模板工厂
 * 关注公众号【奔跑的码畜】，一起进步不迷路
 *
 * @author 第七人格
 * @date 2023/10/30
 */
public class TemplateFactory {

    private TemplateFactory() {
    }

    private static String ENCODING = "UTF-8";

    /**
     * 内置模板默认路径
     */
    private static FreemarkerConfiguration FREEMARKER = new FreemarkerConfiguration("/template");

    public static Template getInstance(String ftl, Boolean useLocalTemplate) throws IOException {
        return useLocalTemplate ? FREEMARKER.getTemplate(ftl, ENCODING) : getCustomTemplate(ftl);
    }

    private static Template getCustomTemplate(String ftl) throws IOException {

        String substring = ftl.substring(0, ftl.lastIndexOf("/"));
        String substring1 = ftl.substring(ftl.lastIndexOf("/", ftl.length()));

        Configuration configuration = new Configuration(Configuration.getVersion());
        FileTemplateLoader fileTemplateLoader = new FileTemplateLoader(new File(substring));
        configuration.setTemplateLoader(fileTemplateLoader);

        return configuration.getTemplate(substring1, ENCODING);
    }


    static class FreemarkerConfiguration extends Configuration {
        public FreemarkerConfiguration(String basePackagePath) {
            super(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
            setDefaultEncoding(ENCODING);
            setClassForTemplateLoading(getClass(), basePackagePath);
        }
    }

}
